package com.yjc.drygoods.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yjc.common.exception.NotWareStockException;
import com.yjc.common.to.*;
import com.yjc.common.utils.R;
import com.yjc.common.vo.ConsumeAttentionCountRelationVo;
import com.yjc.common.vo.MemberRespVo;
import com.yjc.drygoods.order.constant.OrderConstant;
import com.yjc.drygoods.order.dao.OrderDao;
import com.yjc.drygoods.order.entity.OrderEntity;
import com.yjc.drygoods.order.entity.OrderItemEntity;
import com.yjc.drygoods.order.entity.PaymentInfoEntity;
import com.yjc.drygoods.order.enume.OrderStatusEnum;
import com.yjc.common.exception.NotAddrIdException;
import com.yjc.drygoods.order.feign.*;
import com.yjc.drygoods.order.service.OrderItemService;
import com.yjc.drygoods.order.service.OrderService;
import com.yjc.drygoods.order.service.PaymentInfoService;
import com.yjc.drygoods.order.to.CreateOrderTo;
import com.yjc.drygoods.order.vo.*;
import com.yjc.drygoods.order.interceptor.LoginUserInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjc.common.utils.PageUtils;
import com.yjc.common.utils.Query;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    ThreadPoolExecutor threadPool;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Autowired
    SearchFeignService searchFeignService;

    @Autowired
    CouponFeignService couponFeignService;

    private ThreadLocal<OrderSubmitVo> threadLocal = new ThreadLocal<>();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils listWithOrderItems(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        QueryWrapper<OrderEntity> orderQueryWrapper = new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id");


        if (StringUtils.isEmpty((String) params.get("page"))) {
            params.put("page", "1");
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            orderQueryWrapper.eq("status", status);
        }
        String orderCreateTime = (String) params.get("orderCreateTime");
        log.info("orderCreateTime:{}", orderCreateTime);
        if (!StringUtils.isEmpty(orderCreateTime)) {
            String[] times = orderCreateTime.split("_");
            orderQueryWrapper.ge("modify_time", times[0]);
            if (times.length > 1) {
                orderQueryWrapper.le("modify_time", times[1]);
            }
        }
//        log.info("当前需要查询的订单的截止时间：{}", params.get("orderCreateTime"));
        params.put("limit", "5");
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                orderQueryWrapper
        );
        List<OrderEntity> records = page.getRecords();
        List<OrderEntity> orders = records.stream().map(order -> {
            QueryWrapper<OrderItemEntity> orderItems = new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn());
            String key = (String) params.get("key");
            if (!StringUtils.isEmpty(key)) {
                orderItems.and(i -> i.eq("order_sn", key).or().like("sku_name", key));
            }
            List<OrderItemEntity> order_sn = orderItemService
                    .list(orderItems);
            order.setOrderItems(order_sn);
//            log.info("订单项：{}",order.getOrderItems());
            return order;
        }).filter(item -> item.getOrderItems() != null && item.getOrderItems().size() > 0).collect(Collectors.toList());
        page.setRecords(orders);


        return new PageUtils(page);
    }

    /**
     * 修改订单状态
     *
     * @param payAsyncVo
     * @return
     */
    @Override
    public String handleOrderStatus(PayAsyncVo payAsyncVo) {
        //保存流水账单
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setAlipayTradeNo(payAsyncVo.getTrade_no());
        paymentInfo.setOrderSn(payAsyncVo.getOut_trade_no());
        paymentInfo.setPaymentStatus(payAsyncVo.getTrade_status());
        paymentInfo.setCallbackTime(payAsyncVo.getNotify_time());
        paymentInfoService.save(paymentInfo);

        if (payAsyncVo.getTrade_status().equals("TRADE_SUCCESS") || payAsyncVo.getTrade_status().equals("TRADE_FINISHED")) {
            this.baseMapper.updateOrderStatus(payAsyncVo.getOut_trade_no(), OrderStatusEnum.PAYED.getCode());
            //增加该商品的销售量`pms_sku_info`-->sale_count

            //1.获取该订单号下所有订单项
            List<OrderItemEntity> orderItems
                    = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", payAsyncVo.getOut_trade_no()));
            List<SkuInfoTo> skuInfoTos = orderItems.stream().map(orderItem -> {
                SkuInfoTo skuInfoTo = new SkuInfoTo();
                skuInfoTo.setSkuId(orderItem.getSkuId());
                skuInfoTo.setSaleCount(Long.parseLong(orderItem.getSkuQuantity().toString()));
                skuInfoTo.setWeight(orderItem.getWeight());
                return skuInfoTo;
            }).collect(Collectors.toList());
            productFeignService.updateSkuSaleCount(skuInfoTos);

            //更新ES中的销量数据
            R r = searchFeignService.updateEsSaleCount(skuInfoTos);
        }
        return "success";
    }

    @Override
    public List<ConsumeAttentionCountRelationVo> getEveryoneConsumeTotal(List<Long> memberIds) {
        return this.baseMapper.selectEveryoneConsumeTotal(memberIds);
    }

    @Override
    public void updateOrderCommentTime(String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setCommentTime(new Date());
        this.update(orderEntity, new UpdateWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public List<OrderEntity> getAllOrderWithOrderItems() {

        List<OrderEntity> orders = this.list();
        List<OrderEntity> orderRes = orders.stream().map(item -> {
            List<OrderItemEntity> orderItems = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                    .eq("order_sn", item.getOrderSn()));
            item.setOrderItems(orderItems);
            return item;
        }).collect(Collectors.toList());
        return orderRes;
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {

        OrderConfirmVo orderConfirm = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //给异步线程发送需要的请求消息
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        CompletableFuture<Void> memberFuture = CompletableFuture.runAsync(() -> {
            //1.远程调用会员服务，获取收货地址
            RequestContextHolder.setRequestAttributes(requestAttributes);
            R rMember = memberFeignService.getMemberAddress(memberRespVo.getId());
            List<MemberAddressVo> memberAddresses = rMember.getData(new TypeReference<List<MemberAddressVo>>() {
            });
            orderConfirm.setAddress(memberAddresses);
        }, threadPool);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //2.调用远程购物车服务，获取所有选中的购物项
            RequestContextHolder.setRequestAttributes(requestAttributes);
            R rCartItems = cartFeignService.getCurrentUserAllCartItems();
            List<OrderItemVo> orderItemVoList = rCartItems.getData(new TypeReference<List<OrderItemVo>>() {
            });
            orderConfirm.setOrderItems(orderItemVoList);
            //设置购物积分
            Integer integration = memberRespVo.getIntegration();
            Integer buyIntegration = orderItemVoList.size() * 100;
            if (integration < buyIntegration) {
                int i = integration / 100;
                buyIntegration = i * 100;
            }
//            log.info("购物项数量：{}", orderItemVoList.size());
//            log.info("该订单所要扣减的购物积分：{}", buyIntegration);
            orderConfirm.setBuyIntegration(buyIntegration);
        }, threadPool).thenRunAsync(() -> {
            //调用远程库存服务，查询库存时不需要请求参数(这里是Cookie登录信息)
            List<OrderItemVo> orderItems = orderConfirm.getOrderItems();
            List<Long> spuIds = orderItems.stream().map(OrderItemVo::getSpuId).collect(Collectors.toList());
            R skuWare = wareFeignService.getSpuWare(spuIds);
            List<SpuHasStock> data = skuWare.getData(new TypeReference<List<SpuHasStock>>() {
            });
            Map<Long, Boolean> hashStockMap = data.stream().distinct().collect(Collectors.toMap(SpuHasStock::getSpuId, SpuHasStock::getHashStock));
            orderConfirm.setHasStock(hashStockMap);
        }, threadPool);
        String orderToken = UUID.randomUUID().toString().replace("-", "");
        //给redis中保存订单令牌
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), orderToken, 30, TimeUnit.MINUTES);
        //给页面返回订单令牌
        orderConfirm.setOrderToken(orderToken);

        //3.获取优惠券信息(`sms_coupon_history`)
        R rCouponInfo = couponFeignService.getCouponByMemberId(memberRespVo.getId());
        if (rCouponInfo.getCode() == 0) {
            List<CouponTo> data = rCouponInfo.getData(new TypeReference<List<CouponTo>>() {
            });
            orderConfirm.setIntegration(data);
        }
        CompletableFuture.allOf(memberFuture, cartFuture).get();
        //4.设置总的满减和打折金额
        List<OrderItemVo> orderItems = orderConfirm.getOrderItems().stream().map(orderItem -> {
            BigDecimal realAmount = orderItem.getPrice().multiply(new BigDecimal(orderItem.getCount().toString()));
            SkuReductionTo skuReduction = orderItem.getSkuReduction();
            BigDecimal promotionAmount = new BigDecimal("0.0");
            //4.1.1设置打折金额
            if (skuReduction.getFullCount() <= orderItem.getCount()) {
                BigDecimal discount = realAmount.multiply(skuReduction.getDiscount());
                promotionAmount = promotionAmount.add(realAmount.subtract(discount));
                //打完折后的总金额
                realAmount = realAmount.subtract(discount);
            }
            //4.1.2设置满减金额
            if (skuReduction.getFullPrice().compareTo(realAmount) == -1 || skuReduction.getFullPrice().compareTo(realAmount) == 0) {
                promotionAmount = promotionAmount.add(skuReduction.getReducePrice());
                //满减完后的总金额
                realAmount = realAmount.subtract(skuReduction.getReducePrice());
            }
            orderItem.setPromotionAmount(promotionAmount);
            return orderItem;
        }).collect(Collectors.toList());
        orderConfirm.setOrderItems(orderItems);
        return orderConfirm;
    }

    //    @GlobalTransactional
    @Transactional
    @Override
    public OrderSubmitRespVo submitOrder(OrderSubmitVo submitVo) {
        threadLocal.set(submitVo);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderSubmitRespVo orderSubmitRespVo = new OrderSubmitRespVo();
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long execute = redisTemplate.execute(
                new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),
                submitVo.getOrderToken());
        if (execute == 0L) {
            //令牌不通过
            orderSubmitRespVo.setCode(1);
            return orderSubmitRespVo;
        } else {
            //令牌通过
            CreateOrderTo orderTo = createOrder();
            //验价
            BigDecimal payAmount = orderTo.getOrder().getPayAmount();
            BigDecimal payPrice = submitVo.getPayPrice();
            log.info("payAmount:{},payPrice:{}", payAmount, payPrice);
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                //相同
                //保存订单
                saveOrder(orderTo);
                //库存锁定
                WareLockVo wareLockVo = new WareLockVo();
                wareLockVo.setOrderSn(orderTo.getOrder().getOrderSn());
                List<OrderItemVo> orderItemVos = orderTo.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSpuId(item.getSpuId());
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    orderItemVo.setWeight(item.getWeight());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareLockVo.setLocks(orderItemVos);
                R r = wareFeignService.lockStock(wareLockVo);
                if (r.getCode() == 0) {
                    //锁库存成功了
                    orderSubmitRespVo.setOrder(orderTo);
                    orderSubmitRespVo.setCode(0);
                    //模拟异常
//                    int a = 10 / 0;
                    //发送订单取消消息
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", orderTo.getOrder());
                } else {
                    //锁库存失败了
                    String msg = (String) r.get("msg");
                    throw new NotWareStockException(msg);
                }

            } else {
                //订单应付金额与结算页应付金额不同
                orderSubmitRespVo.setCode(2);
            }
            return orderSubmitRespVo;
        }
    }

    @Override
    public OrderEntity getOrderInfoByOrderSn(String orderSn) {

        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public void closeOrder(OrderEntity or) {
        OrderEntity order = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", or.getOrderSn()));
        if (order != null) {
            if (order.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
                //取消订单
                OrderEntity updateOrder = new OrderEntity();
                updateOrder.setId(order.getId());
                updateOrder.setStatus(OrderStatusEnum.CANCLED.getCode());
                this.updateById(updateOrder);

                //发送解锁库存消息
                OrderTo orderTo = new OrderTo();
                BeanUtils.copyProperties(order, orderTo);
                orderTo.setStatus(OrderStatusEnum.CANCLED.getCode());
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            }
        }
    }

    @Override
    public PayVo getPayVo(String orderSn) {
//        private String out_trade_no; // 商户订单号 必填
//        private String subject; // 订单名称 必填
//        private String total_amount;  // 付款金额 必填
//        private String body; // 商品描述 可空
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        BigDecimal payAmount = order.getPayAmount();
        BigDecimal bigDecimal = payAmount.setScale(2, BigDecimal.ROUND_UP);//必须保证小数点后为2位数
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(orderSn);

        List<OrderItemEntity> orderItems = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItem = orderItems.get(0);
        payVo.setSubject(orderItem.getSkuName());
        payVo.setBody(orderItem.getSkuAttrsVals());
        return payVo;
    }


    /**
     * 保存订单数据
     *
     * @param orderTo
     */
    private void saveOrder(CreateOrderTo orderTo) {
        OrderEntity order = orderTo.getOrder();
        order.setModifyTime(new Date(System.currentTimeMillis()));
        this.save(order);
        orderItemService.saveBatch(orderTo.getOrderItems());
    }

    private CreateOrderTo createOrder() {
        CreateOrderTo createOrderTo = new CreateOrderTo();

        //1.生成订单号（避免订单号过长，截串）
        String orderSn = IdWorker.getTimeId();


        //2.构建订单
        OrderEntity order = buildOrder();
        order.setOrderSn(orderSn);
        createOrderTo.setOrder(order);

        //3.构建订单项
        List<OrderItemEntity> orderItems = buildOrderItems(orderSn);
        createOrderTo.setOrderItems(orderItems);

        //4.计算价格相关信息
        computePrice(order, orderItems);

        return createOrderTo;

    }

    private void computePrice(OrderEntity order, List<OrderItemEntity> orderItems) {

        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        BigDecimal totalAmount = new BigDecimal("0.0");
        BigDecimal promotionAmount = new BigDecimal("0.0");
        //优惠券优惠金额
        BigDecimal couponAmount = threadLocal.get().getCouponAmount();
        //满减与打折优惠金额和
        BigDecimal promotionAmountCollection = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");

        //下单时使用的积分
        Integer useIntegration = 0;

        for (OrderItemEntity orderItem : orderItems) {
            totalAmount = totalAmount.add(orderItem.getRealAmount());
            promotionAmount = promotionAmount.add(orderItem.getPromotionAmount());
//            couponAmount = couponAmount.add(orderItem.getCouponAmount());
            integration = integration.add(new BigDecimal(orderItem.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(orderItem.getGiftGrowth().toString()));
            useIntegration += (orderItem.getIntegrationAmount().intValue() * 10);
        }
        //订单总额
        order.setTotalAmount(totalAmount);
        log.info("totalAmount:{}", totalAmount);
        //各种优惠金额
        order.setPromotionAmount(promotionAmount);
        order.setCouponAmount(couponAmount);
        //应付金额
        order.setPayAmount(totalAmount.add(order.getFreightAmount()));
        //成长值
        //TODO 支付成功后要加成长值
        order.setGrowth(growth.intValue());
        //获得的积分
        //TODO 支付成功后要加获得的积分
        order.setIntegration(integration.intValue());
        //删除状态
        order.setDeleteStatus(0);//未删除
        //TODO 使用的积分
        Integer memberIntegration = memberRespVo.getIntegration();
        if (memberIntegration < useIntegration) {
            log.info("memberIntegration:{},useIntegration:{}", memberIntegration, useIntegration);
            //用户积分不够,直接放弃使用积分优惠
            //积分抵扣金额
            order.setIntegrationAmount(new BigDecimal("0.0"));
            //修改订单总额
            int tempVal = useIntegration / 10;
            order.setTotalAmount(order.getTotalAmount().add(new BigDecimal(tempVal + "")));
            //修改应付总额
            order.setPayAmount(order.getTotalAmount().add(order.getFreightAmount()));
            log.info("PayAmount:{}", order.getPayAmount());
            //还原该订单的所有订单项的真正金额
            List<OrderItemEntity> collect = orderItems.stream().map(item -> {
                item.setRealAmount(item.getRealAmount().add(new BigDecimal("10.0")));
                return item;
            }).collect(Collectors.toList());
            orderItems = collect;
        } else {
            //TODO 支付成功后要扣减已使用的积分数量(积分数量和扣减金额是100:10,定死)
            order.setUseIntegration(useIntegration);
            order.setIntegrationAmount(new BigDecimal(useIntegration / 10 + ""));
        }

    }


    /**
     * 构建所有订单项(框架)
     *
     * @param orderSn
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        R r = cartFeignService.getCurrentUserAllCartItems();
        //获取到所有购物车项
        List<OrderItemVo> orderItemVos = r.getData(new TypeReference<List<OrderItemVo>>() {
        });

        if (orderItemVos != null && orderItemVos.size() > 0) {
            R couponRes = couponFeignService.getAllSpuCoupon();
            if (couponRes.getCode() == 0) {
                List<SpuBoundTo> data = couponRes.getData(new TypeReference<List<SpuBoundTo>>() {
                });
                //所有spu商品的成长积分
                Map<Long, BigDecimal> growBoundMap
                        = data.stream().collect(Collectors.toMap(SpuBoundTo::getSpuId, SpuBoundTo::getGrowBounds));
                //所有spu商品的购物积分
                Map<Long, BigDecimal> buyBoundMap = data.stream().collect(Collectors.toMap(SpuBoundTo::getSpuId, SpuBoundTo::getBuyBounds));
                List<OrderItemEntity> collect = orderItemVos.stream().map(item -> {
                    OrderItemEntity orderItemEntity = buildOrderItem(item, growBoundMap, buyBoundMap);
                    //5.订单号
                    orderItemEntity.setOrderSn(orderSn);
                    return orderItemEntity;
                }).collect(Collectors.toList());
                return collect;
            }
        }
        return null;
    }

    private OrderItemEntity buildOrderItem(OrderItemVo item, Map<Long, BigDecimal> growBoundMap, Map<Long, BigDecimal> buyBoundMap) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderItemEntity orderItem = new OrderItemEntity();
        //1.商品sku信息
        orderItem.setSkuId(item.getSkuId());
        orderItem.setSkuName(item.getTitle());
        orderItem.setSkuPic(item.getImage());
        orderItem.setSkuPrice(item.getPrice());
        orderItem.setSkuQuantity(item.getCount());
        orderItem.setWeight(item.getWeight());
        orderItem.setSkuAttrsVals(StringUtils.collectionToDelimitedString(item.getSkuAttr(), ";"));
        //2.商品spu信息
        //调用远程商品sku服务，获取spu信息
        R rSpuInfo = productFeignService.getSpuInfoBySkuId(item.getSkuId());
        SpuInfoVo spuInfo = rSpuInfo.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItem.setSpuId(spuInfo.getId());
        orderItem.setSpuName(spuInfo.getSpuName());
//        R info = productFeignService.info(spuInfo.getBrandId());
//        //调用远程商品品牌服务，获取品牌信息
//        BrandVo brand = info.getData("brand", new TypeReference<BrandVo>() {
//        });
//        orderItem.setSpuBrand(brand.getName());
        orderItem.setCategoryId(spuInfo.getCatalogId());
        //3.商品提供的积分信息(`sms_spu_bounds`)
        //设置成长积分
        orderItem.setGiftGrowth(growBoundMap.get(spuInfo.getId()) == null ? 0 : growBoundMap.get(spuInfo.getId()).intValue());
        orderItem.setGiftIntegration(buyBoundMap.get(spuInfo.getId()) == null ? 0 : buyBoundMap.get(spuInfo.getId()).intValue());
        //4.商品优惠信息
        //4.1促销优惠金额
        BigDecimal realAmount = orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuQuantity().toString()));
        log.info("realAmount:{}", realAmount);
        SkuReductionTo skuReduction = item.getSkuReduction();
        BigDecimal promotionAmount = new BigDecimal("0.0");
        //4.1.1设置打折金额
        if (skuReduction.getFullCount() <= orderItem.getSkuQuantity()) {
            BigDecimal discount = realAmount.multiply(skuReduction.getDiscount());
            promotionAmount = promotionAmount.add(realAmount.subtract(discount));
        }
        //4.1.2设置满减金额
        if (skuReduction.getFullPrice().compareTo(realAmount) == -1 || skuReduction.getFullPrice().compareTo(realAmount) == 0) {
            promotionAmount = promotionAmount.add(skuReduction.getReducePrice());
        }
        orderItem.setPromotionAmount(promotionAmount);

        //4.2优惠券优惠金额(因优惠券优惠整个订单比较合适，每个订单项都有优惠券不太合适，所以订单项优惠券金额设为0)
        orderItem.setCouponAmount(new BigDecimal("0.0"));
        //4.3积分优惠金额
        orderItem.setIntegrationAmount(new BigDecimal("10.0"));


        //4.4所有优惠叠加后的真正应付金额
        realAmount = realAmount
                .subtract(orderItem.getPromotionAmount())
                .subtract(orderItem.getCouponAmount())
                .subtract(orderItem.getIntegrationAmount());
        orderItem.setRealAmount(realAmount);
        log.info("最后的realAmount:{}", realAmount);
        return orderItem;
    }

    /**
     * 构建订单
     *
     * @return
     */
    private OrderEntity buildOrder() {
        OrderSubmitVo orderSubmitVo = threadLocal.get();
        OrderEntity order = new OrderEntity();
        if (orderSubmitVo.getAddrId() == null) {
            throw new NotAddrIdException("请选择收货地址或新增收货地址");
        }
        R rMemberAddr = memberFeignService.getFare(orderSubmitVo.getAddrId());

        FareVo data = rMemberAddr.getData(new TypeReference<FareVo>() {
        });
        //设置用户id
        order.setMemberId(data.getAddress().getMemberId());
        //设置用户名
        order.setMemberUsername(data.getAddress().getName());
        //设置运费
        order.setFreightAmount(data.getFare());

        //设置基本属性
        order.setReceiverCity(data.getAddress().getCity());
        order.setReceiverDetailAddress(data.getAddress().getDetailAddress());
        order.setReceiverName(data.getAddress().getName());
        order.setReceiverPhone(data.getAddress().getPhone());
        order.setReceiverPostCode(data.getAddress().getPostCode());
        order.setReceiverProvince(data.getAddress().getProvince());
        order.setReceiverRegion(data.getAddress().getRegion());

        //设置订单状态
        order.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        //设置自动确认时间
        order.setAutoConfirmDay(7);

        return order;
    }

}